package com.cn.ryc.service;

import com.cn.ryc.mapper.VideoMapper;
import com.cn.ryc.model.Video;
import com.cn.ryc.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class VideoService {

    @Autowired
    private VideoMapper videoMapper;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_DATE_TIME;

    public ResponseEntity<ApiResponse<String>> insertVideoInfo(String videoUrl, String videoName,
                                                               String uploadTime, Long userId, String fileSize) {
        try {
            // 尝试解析上传时间，支持多种格式
            LocalDateTime uploadDateTime;
            try {
                // 首先尝试解析ISO格式
                uploadDateTime = LocalDateTime.parse(uploadTime, isoFormatter);
            } catch (Exception e) {
                try {
                    // 如果失败，尝试使用标准格式
                    uploadDateTime = LocalDateTime.parse(uploadTime, formatter);
                } catch (Exception ex) {
                    uploadDateTime = LocalDateTime.now();
                }
            }

            // 创建Video对象
            Video video = new Video();
            video.setUrl(videoUrl);
            video.setOriginalName(videoName);
            video.setFileSize(fileSize);
            video.setUploadTime(uploadDateTime);
            video.setUserId(userId);

            // 插入记录
            videoMapper.insertVideo(video);

            return ResponseEntity.ok(ApiResponse.success("视频信息保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }
}